package com.minggo.charmword.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.Toast;

import com.baidu.mobstat.StatService;
import com.minggo.charmword.R;
import com.minggo.charmword.adapter.ShakeFindAdapter;
import com.minggo.charmword.logic.ShakeFindUtil;
import com.minggo.charmword.model.Around;
import com.minggo.charmword.service.CharmWordApplication;
import com.minggo.charmword.util.PlaySound;
import com.minggo.charmword.util.ShakeListener;
import com.minggo.charmword.util.ShakeListener.OnShakeListener;

/**
 * 摇一摇
 * 
 * @author minggo
 * @date 2014-10-9 下午4:36:45
 */
@SuppressWarnings("deprecation")
public class ShakeFindActivity extends Activity {

	private ShakeListener mShakeListener = null;
	private Vibrator mVibrator;
	private RelativeLayout mImgUp;
	private RelativeLayout mImgDn;
	private RelativeLayout mTitle;
	private AssetManager assetManager;
	private SlidingDrawer mDrawer;
	private Button mDrawerBtn;
	private List<Around> aroundList = new ArrayList<Around>();
	private ShakeFindAdapter shakeFindAdapter;
	private ShakeFindUtil shakeFindUtil;
	private ProgressBar loadPb;
	private View backV;
	private ListView shakeLv;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shake);

		assetManager = this.getResources().getAssets();
		
		mVibrator = (Vibrator) getApplication().getSystemService(VIBRATOR_SERVICE);

		mImgUp = (RelativeLayout) findViewById(R.id.shakeImgUp);
		mImgDn = (RelativeLayout) findViewById(R.id.shakeImgDown);
		mTitle = (RelativeLayout) findViewById(R.id.head);
		mDrawer = (SlidingDrawer) findViewById(R.id.slidingDrawer1);
		mDrawerBtn = (Button) findViewById(R.id.handle);

		loadPb = (ProgressBar) findViewById(R.id.pb_loading);
		loadPb.setVisibility(View.GONE);
		backV = findViewById(R.id.lo_shake_back);
		shakeLv = (ListView) findViewById(R.id.lv_shake);
		
		backV.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});

		mDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
			public void onDrawerOpened() {
				mDrawerBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.shake_report_dragger_down));
				TranslateAnimation titleup = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f,
						Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
						-1.0f);
				titleup.setDuration(200);
				titleup.setFillAfter(true);
				mTitle.startAnimation(titleup);
				mShakeListener.stop();
				if (shakeFindAdapter!=null) {
					shakeFindAdapter.recycleFinalBitmap();
				}
			}
		});
		/* 设定SlidingDrawer被关闭的事件处理 */
		mDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
			public void onDrawerClosed() {
				mDrawerBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.shake_report_dragger_up));
				TranslateAnimation titledn = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f,
						Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF,
						0f);
				titledn.setDuration(200);
				titledn.setFillAfter(false);
				mTitle.startAnimation(titledn);
				mShakeListener.start();
			}
		});

		mShakeListener = new ShakeListener(this);
		mShakeListener.setOnShakeListener(new OnShakeListener() {
			public void onShake() {
				startAnim(); // 开始 摇一摇手掌动画
				mShakeListener.stop();
				if (startVibrato()) {

					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							mVibrator.cancel();
							mShakeListener.start();

						}
					}, 800);
				}

			}
		});
		CharmWordApplication.allActivities.add(this);
	}

	/**
	 * 请求数据
	 */
	private void requestData() {
		
		//shakeFindUtil = new ShakeFindUtil(handler);
		//shakeFindUtil.execute();
		
		final List<Around> list = new ArrayList<Around>();
		for (int i = 0; i < 5; i++) {
			Around around = new Around();
			around.userName = "w1000"+i;
			around.userAvatar = "http://b.img.youboy.com/201010/12/g3_6576976.jpg";
			around.word = "Word"+i;
			around.explain = "n.单词"+i;
			around.simpleAddess = "广东广州"+i;
			list.add(around);
		}
		
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				//handler.sendEmptyMessage(ShakeFindUtil.GET_SHAKE_FIND);
				handler.obtainMessage(ShakeFindUtil.GET_SHAKE_FIND, list).sendToTarget();
			}
		}, 1800);
	}

	/**
	 * 刷新获取到的数据
	 * @param list
	 */
	private void refreshDataUI(List<Around> list){
		try {
			PlaySound.play("sound/shake_match.mp3", assetManager);
		} catch (IOException e) {
			e.printStackTrace();
		}
		aroundList.clear();
		aroundList.addAll(list);
		if (!mDrawer.isOpened()) {
			mDrawer.animateOpen();
		}
		if (shakeFindAdapter==null) {
			shakeFindAdapter = new ShakeFindAdapter(this, aroundList);
			shakeLv.setAdapter(shakeFindAdapter);
		}else{
			shakeFindAdapter.notifyDataSetChanged();
		}
	}
	
	private Handler handler = new Handler(new Callback() {

		@SuppressWarnings("unchecked")
		@Override
		public boolean handleMessage(Message msg) {
			loadPb.setVisibility(View.GONE);
			switch (msg.what) {
			case ShakeFindUtil.GET_SHAKE_FIND:
				if (msg.obj!=null&&!((List<Around>)msg.obj).isEmpty()) {
					System.out.println("不为空");
					refreshDataUI((List<Around>)msg.obj);
				}else{
					System.out.println("为空");
					Toast.makeText(ShakeFindActivity.this, "没有同时摇一摇的伙伴", Toast.LENGTH_LONG).show();
				}
				break;
			default:
				break;
			}
			return false;
		}
	});

	public void startAnim() { // 定义摇一摇动画动画
		AnimationSet animup = new AnimationSet(true);
		TranslateAnimation mytranslateanimup0 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f,
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -0.5f);
		mytranslateanimup0.setDuration(1000);
		TranslateAnimation mytranslateanimup1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f,
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, +0.5f);
		mytranslateanimup1.setDuration(1000);
		mytranslateanimup1.setStartOffset(1000);
		animup.addAnimation(mytranslateanimup0);
		animup.addAnimation(mytranslateanimup1);
		mImgUp.startAnimation(animup);

		AnimationSet animdn = new AnimationSet(true);
		TranslateAnimation mytranslateanimdn0 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f,
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, +0.5f);
		mytranslateanimdn0.setDuration(1000);
		TranslateAnimation mytranslateanimdn1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f,
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -0.5f);
		mytranslateanimdn1.setDuration(1000);
		mytranslateanimdn1.setStartOffset(1000);
		animdn.addAnimation(mytranslateanimdn0);
		animdn.addAnimation(mytranslateanimdn1);
		mytranslateanimdn1.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {

			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				loadPb.setVisibility(View.VISIBLE);
				requestData();
			}
		});
		mImgDn.startAnimation(animdn);
	}

	public boolean startVibrato() { // 定义震动
		mVibrator.vibrate(new long[] { 500, 200, 500, 200 }, -1); // 第一个｛｝里面是节奏数组，
																	// 第二个参数是重复次数，-1为不重复，非-1则从pattern的指定下标开始重复
		try {
			PlaySound.play("sound/shake_sound_male.mp3", assetManager);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}

	public void linshi(View v) { // 标题栏
		startAnim();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mShakeListener != null) {
			mShakeListener.stop();
		}
	}
	@Override
	public void onBackPressed() {
		if (shakeFindAdapter!=null) {
			shakeFindAdapter.recycleFinalBitmap();
		}
		super.onBackPressed();
	}
	@Override
	protected void onPause() {
		super.onPause();
		StatService.onPause(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		StatService.onResume(this);
	}
}